package com.freemalll.merchant.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.freemalll.merchant.common.CommonEnum;
import com.freemalll.merchant.domain.entity.MerAuthFlow;
import com.freemalll.merchant.service.merchantAuditManage.MerAuthFlowService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
@Profile(value = {"test", "pro"})
public class MerAuthFlowExpireJob {

    private final MerAuthFlowService merAuthFlowService;

    /**
     * 每天凌晨1点执行
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void expireSupplementAuthFlow() {
        log.info("[MerAuthFlowExpireJob] 开始检查超期补充件...");
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expireTime = now.minusDays(30);
        List<MerAuthFlow> expiredList = merAuthFlowService.list(new LambdaQueryWrapper<MerAuthFlow>()
                .eq(MerAuthFlow::getAuthStatus, CommonEnum.auditType.SUPPLEMENTARY_PARTS.name())
                .lt(MerAuthFlow::getSupplementTime, Date.from(expireTime.atZone(ZoneId.systemDefault()).toInstant()))
        );
        for (MerAuthFlow flow : expiredList) {
            flow.setAuthStatus(CommonEnum.auditType.WITHDRAW.name());
            flow.setCancelTime(LocalDateTime.now());
            flow.setRemarks("超过30天自动过期");
        }
        merAuthFlowService.updateBatchById(expiredList);
        log.info("[MerAuthFlowExpireJob] 处理完成，过期数量:{}", expiredList.size());
    }
}
